package com.hs.room.repository

import android.content.Context
import com.hs.common.dto.SysDeptDto
import com.hs.common.repository.IDeptRepository
import com.hs.room.AppDatabase
import com.hs.room.mapper.DeptMapper
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject

/**
 * 部门的
 */
class DeptRoomRepository @Inject constructor(
    @ApplicationContext var context: Context,
    val database: AppDatabase
) : IDeptRepository {


    override suspend fun insertDept(sysDeptDto: SysDeptDto) {
        database.sysDeptDao().insert(DeptMapper.INSTANCE.deptDtoToDept(sysDeptDto))
    }

    override fun getAllDept(): Flow<List<SysDeptDto>> {
        return flow {
            val deptFlow = database.sysDeptDao().getAllDeptList()
                .filter { it.isNotEmpty() }
                .map { DeptMapper.INSTANCE.deptListToDeptDTOs(it) }
            emitAll(deptFlow)
        }.catch { e ->
            // 进行异常处理
            println("Error occurred while fetching user data: $e")
        }
    }

    override suspend fun selectByCode(code: String): SysDeptDto {
        return DeptMapper.INSTANCE.deptToDeptDTO(database.sysDeptDao().selectByCode(code))
    }


}
